package org.budo.shiro.session.dao.jedis;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;

/**
 * 工具
 * 
 * @author li
 * @version 1 (2015年11月9日 下午8:27:27)
 * @since Java7
 */
public class JedisSessionDaoUtil {
    private static final Logger log = Slf4j.getLogger();

    public static Object deserialize(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
            return objectInputStream.readObject();
        } catch (IOException ex) {
            throw new IllegalArgumentException("Failed to deserialize object", ex);
        } catch (ClassNotFoundException ex) {
            log.error("RedisShiroCacheUtil deserialize() ClassNotFoundException " + ex, ex);
            throw new IllegalStateException("Failed to deserialize object type", ex);
        }
    }

    public static byte[] serialize(Object object) {
        if (object == null) {
            return null;
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(object);
            objectOutputStream.flush();
        } catch (IOException ex) {
            throw new IllegalArgumentException("Failed to serialize object of type: " + object.getClass(), ex);
        }
        return byteArrayOutputStream.toByteArray();
    }
}